//筛选房源条件
var flag=true;
$(function(){
	$(".back").on("touchend", function (e) {
    	e.preventDefault();
	    e.stopPropagation();
	    window.history.back();
	});
	//查看成交房源
	$('.check-sale').on("touchend", function (e) {
		e.preventDefault();
	    e.stopPropagation();
	    var hangSearchVal= common.getLocalData("hangHistorySearchRecord");
	    window.location.href="villageSearchResult.html?hangSearchVal="+hangSearchVal[0];
	});
//加载所有的挂牌房源数据
    var $houseSaleListPanel=$("#house-saleList");
    var $searchVillageFail=$('.search-village-fail');
    var globalHost=common.globalHost;
    var listPort=common.queryVillageSaleHouse;
    //获取villageId;
    var villageId=common.getQueryString('villageId');
    //小区标题
    $("#village-title").html(villageId)
    var documentHeight=0;
    var windowHeight=0;
    var $resMsg=$("#res-msg");
    var sendData={};
 	sendData={
        pageIndex:1,
        pageSize:10,
        villageId:villageId
    };
    var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
    var url=globalHost+listPort;
    historyControl.layerShow();
    requestData();
    function requestData() {
    	// historyControl.layerShow();
        $.ajax({
            data:sendData,
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType:"json",
            url:url,
            success:function(data){
            	historyControl.layerHide();
                $resMsg.text("").hide();
                if(typeof data==="string"){
                    data=JSON.parse(data);
                }
                if(data.totalNumber==0){
                	$houseSaleListPanel.hide();
                	$searchVillageFail.show();
                }else{
                	$houseSaleListPanel.show();
                	$searchVillageFail.hide();
                	data=data.data;
                	 if(!data.length){
	                    $resMsg.text("已经没有更多信息了").show();
	                }else{
	                    var responseDom=buildListDomOfMobileByDataList({
	                        loadingSelector:$resMsg,
	                        imgBasePath:globalHost,
	                        pageTargetType:"_self",
	                        dataList:data
	                    });
	                    $houseSaleListPanel.append(responseDom);
	                    documentHeight=$(document).height();
	                    sendData.pageIndex++;
	                }
                }
               
            },
            timeout:10000,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
    			historyControl.layerHide();
                historyControl.errDialog("网络不畅，请稍后重试");
            }
        });
    }
    //价格排序
	var $priceSort = $('.price-sort-child');
	checkBox({
		targetSelector:$priceSort,
		chosen:'chosen'
	});
	function checkBox(options){
		var $targetSelector=$(options.targetSelector);
		var chosen=options.chosen;
			$targetSelector.children().off('tap').on('tap',function(e){
				var $this=$(this);
				$this.hasClass(chosen)?$this.removeClass(chosen):$this.addClass(chosen).siblings().removeClass(chosen);
				e.preventDefault();
				return false;
			})
	}
	//来源;
	var $sourceSort=$('.source-sort-child');
	checkBox({
		targetSelector:$sourceSort,
		chosen:'active'
	});
	//清空条件
	var $parentNav=$('.parent-list');
	var $moreSort=$('#more-sort');
	var $clearCheck=$('.clear-check');
	var $sureCheck=$('.sure-check');
	var $houseSourceInput=$('#houseSource');
	var $houseSortInput=$('#sortType');
	var $myForm=$('#myform');
	var $more=$('.more');
	$clearCheck.off('tap').on('tap',function(e){
		$moreSort.find('.chosen').removeClass('chosen');
		$moreSort.find('.active').removeClass('active');
		//隐藏div
		$moreSort.hide();
		$more.hasClass('marker')?$more.removeClass('marker').html("更多"):null;
		$more.hasClass('clear-marker')?$more.removeClass('clear-marker').html("更多"):null;
		historyControl.maskHide();
		// 清空隐藏域
		$houseSourceInput.val('');
		$houseSortInput.val(0);
		sendData={
	        pageIndex:1,
	        pageSize:10,
	        villageId:villageId
	    };
		var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
		$houseSaleListPanel.html('');
		historyControl.layerShow();
        $searchVillageFail.hide();
        $resMsg.text('').hide();
		requestData();
		e.preventDefault();
		return false;
	})
	//确定点击按钮
	$sureCheck.off('tap').on('tap',function(e){
		var dataValue=[];
		//先清空隐藏域
		$houseSourceInput.val('');
		$houseSortInput.val(0);
		var $chosenArr=$($moreSort.find('.chosen'));
		var $activeArr=$($sourceSort.find('.active'));
		//给隐藏域赋值
		$houseSortInput.val($chosenArr.attr('data-value'));
		$houseSourceInput.val($activeArr.attr('data-value'));
		//排序必须有值
		if($chosenArr.length==0){
			$houseSortInput.val(0);	
		}
		//样式多选添加
		if($chosenArr.length>0&&$activeArr.length===0){
			var chosenHtml= $chosenArr.html();
			$more.html(chosenHtml);
		}else if($activeArr.length>0&&$chosenArr.length===0){
			var activeHtml= $activeArr.html();
			$more.html(activeHtml);
		}else if($chosenArr.length>0&&$activeArr.length>0){
			$more.html("多选");
		}else{
			$more.removeClass('marker');
			$more.removeClass('clear-marker');
			$more.html("更多");
		}
		//隐藏div
		$moreSort.hide();
		$more.hasClass('marker')?$more.removeClass('marker').addClass('clear-marker'):null;
		historyControl.maskHide();
		sendData={
	        pageIndex:1,
	        pageSize:10,
	        villageId:villageId
	    };
		var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
		$houseSaleListPanel.html('');
		historyControl.layerShow();
		$searchVillageFail.hide();
        $resMsg.text('').hide();
		requestData();
		e.preventDefault();
		return false;
	});
	//筛选条件的显示与隐藏
	$parentNav.children('li').off('tap').on('tap',function(e){
		var $this=$(this);
		var formHide=$myForm.find('.form-hide');
		var index = $this.index();
		if($this.hasClass('marker')){
			formHide.hide();
			$this.removeClass('marker');
			formHide.eq(index)[0].style.display==="none"?historyControl.maskHide():historyControl.maskShow();
		}else if($this.hasClass('clear-marker')){
			$this.siblings().removeClass('marker');
			if(formHide.eq(index)[0].style.display==="none"){
				formHide.hide()&&formHide.eq(index).slideDown(200);
				historyControl.maskShow();
			}else{
				formHide.hide();
				historyControl.maskHide();
			}	
		}else{
			formHide.eq(index)[0].style.display==="none"?historyControl.maskShow():historyControl.maskHide();
			formHide.hide()&&formHide.eq(index).slideDown(200);
			$this.addClass('marker').siblings().removeClass('marker');
			historyControl.maskShow();
		}
		// if($this.hasClass('marker')){
		// 	formHide.hide();
		// 	$this.removeClass('marker');
		// 	formHide.eq(index)[0].style.display==="none"?historyControl.maskHide():historyControl.maskShow();
		// }else if($this.hasClass('clear-marker')){
		// 	if(formHide.eq(index)[0].style.display==="none"){
		// 		formHide.hide()&&formHide.eq(index).slideDown(200);
		// 		historyControl.maskShow();
		// 	}else{
		// 		formHide.hide();
		// 		historyControl.maskHide();
		// 	}	
		// }else{
		// 	formHide.eq(index)[0].style.display==="none"?historyControl.maskShow():historyControl.maskHide();
		// 	formHide.hide()&&formHide.eq(index).slideDown(200);
		// 	$this.addClass('marker').siblings().removeClass('marker');
		// 	historyControl.maskShow();
		// }
		//阻止事件冒泡，防止手指滑动的时候屏幕下面的层滑动；
		formHide.off("touchmove").on("touchmove",function(ev){
			ev.stopPropagation();
			ev.preventDefault();
			return false;
		});
		e.preventDefault();
		return false;
	});
	//总价
	var $totalPrice=$('#total-price');
	var $totalMaxInput=$('#totalMax');
	var $totalMinInput=$('#totalMin');
	checkChild({
		targetSelector:$totalPrice,
		parentSelector:$parentNav,
		MaxInput:$totalMaxInput,
		MinInput:$totalMinInput
	})
	//面积
	var $houseArea=$('#house-area');
	var $sizeMaxInput=$('#sizeMax');
	var $sizeMinInput=$('#sizeMin');
	checkChild({
		targetSelector:$houseArea,
		parentSelector:$parentNav,
		MaxInput:$sizeMaxInput,
		MinInput:$sizeMinInput
	})
	//筛选条件给隐藏域赋值总价和面积
	function checkChild(options){
		var $targetSelector=$(options.targetSelector);
		var $MaxInput=$(options.MaxInput);
		var $MinInput=$(options.MinInput);
		var $parentSelector=$(options.parentSelector);
		$targetSelector.find('li').off('tap').on('tap',function(e){
			var $this=$(this);
			var parentId=$targetSelector.attr("id");
			var clearMarker=$parentSelector.find('li').hasClass('clear-marker');
			var marker=$parentSelector.find('li').hasClass('marker');
			$this.hasClass('check')?null:$this.addClass('check').siblings().removeClass('check');
			if(!!marker&&parentId==="total-price"){
				$(".totalHouse").removeClass('marker').addClass('clear-marker').html($this.html());
			}else if(!!marker&&parentId==="house-area"){
				$(".houseArea").removeClass('marker').addClass('clear-marker').html($this.html());
			}else if(!!clearMarker&&parentId==="total-price"){
				$(".totalHouse").html($this.html());
			}else if(!!clearMarker&&parentId==="house-area"){
				$(".houseArea").html($this.html());
			};
			historyControl.maskHide();
			//给隐藏域赋值
			$MaxInput.val('');
			$MinInput.val('');
			var dataValue = $this.attr('data-value');
			if(dataValue.indexOf('-')>-1){
				$MaxInput.val(dataValue.split('-')[1]);
				$MinInput.val(dataValue.split('-')[0]);
			}else{
				$MaxInput.val('');
				$MinInput.val('');
			}
			$this.parent().hide();
			sendData={
		        pageIndex:1,
		        pageSize:10,
		        villageId:villageId
		    };
			var formData=common.getSendDataByForm('form');
			sendData = $.extend({}, sendData, formData);
			$houseSaleListPanel.html('');
			historyControl.layerShow();
			$searchVillageFail.hide();
        	$resMsg.text('').hide();
			requestData();
			e.preventDefault();
			return false;
		})
	}
	//房屋类型的选择
	var $checkUl = $('#house-type');
	var $clearCheck=$('.clear-checkHouseType');
	var $houseType=$('#houseType');
	var $checkHouseType=$('.checkHouseType');
	var $houseTypeOli=$('.houseType');
	$checkUl.children('li').off('tap').on('tap',function(e){
		var $this=$(this);
		$this.hasClass('chosen')?$this.removeClass('chosen'):$this.addClass('chosen');
		e.preventDefault();
		return false;
	});
	//点击不限按钮清空复选
	$clearCheck.off('tap').on('tap',function(e){
		var $this=$(this);
		var clearMarker=$houseTypeOli.hasClass('clear-marker');
		$houseType.val('');
		$this.next().children('li').removeClass('chosen').children('i').removeClass('chosen')&&$this.parent().hide();
		$this.addClass('chosen');
		$houseType.val($this.attr('data-value'));
		$houseTypeOli.hasClass('marker')?$houseTypeOli.removeClass('marker').addClass('clear-marker').html("不限"):null;
		!!clearMarker?$houseTypeOli.html("不限"):null;
		historyControl.maskHide();
		sendData={
	        pageIndex:1,
	        pageSize:10,
	        villageId:villageId
	    };
		var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
		$houseSaleListPanel.html('');
		historyControl.layerShow();
		$searchVillageFail.hide();
        $resMsg.text('').hide();
		requestData();
		e.preventDefault();
		return false;
	})
	//点击确定按钮添加隐藏域
	$checkHouseType.off('tap').on('tap',function(e){
		var checkArr=[];
		var $this=$(this);
		$houseType.val('');
		var oParentUl=$this.prev().children('li');
		for(var i=0;i<oParentUl.length;i++){
			if($(oParentUl[i]).hasClass('chosen')){
				checkArr.push($(oParentUl[i]).attr('data-value'));
			}
		}
		//当点击不选择时，默认为0
		checkArr.length===0?$houseType.val('0'):$houseType.val(checkArr);
		$this.parent().hide();
		var parentId=$checkHouseType.parent().attr("id");
		var clearMarker=$houseTypeOli.hasClass('clear-marker');
		var marker=$houseTypeOli.hasClass('marker');
		var showContent='';
		$houseTypeOli.hasClass('marker')?$houseTypeOli.removeClass('marker').addClass('clear-marker'):null;
		if(!!marker){
			if(checkArr.length===1){
				showContent=$this.prev().children(".chosen").html();
			}else if(checkArr.length>1){
				showContent='多选';
			}else{
				$clearCheck.removeClass('chosen');
				$houseTypeOli.removeClass('marker');
				$houseTypeOli.removeClass('clear-marker');
				showContent="房型";
			}
		}else if(!!clearMarker&&parentId==="search-house-type"){
			if(checkArr.length===1){
				showContent=$this.prev().children(".chosen").html();
			}else if(checkArr.length>1){
				showContent='多选';
			}else{
				$clearCheck.removeClass('chosen');
				$houseTypeOli.removeClass('marker');
				$houseTypeOli.removeClass('clear-marker');
				showContent="房型";
			}
		};
		historyControl.maskHide();
		$houseTypeOli.html(showContent);	
		if(checkArr.length>0){
			$clearCheck.removeClass('chosen');
		}
		sendData={
	        pageIndex:1,
	        pageSize:10,
	        villageId:villageId
	    };
		var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
		$houseSaleListPanel.html('');
		historyControl.layerShow();
		$searchVillageFail.hide();
        $resMsg.text('').hide();
		requestData();
		e.preventDefault();
		return false;
	});
	$(window).on("scroll",function (e) {
        windowHeight=$(window).height();
        if($(this).scrollTop()+windowHeight==documentHeight){
        	if(flag){
        		$resMsg.html('<span class="loading"></span>正在加载中呦~~').show();
        		requestData();
        	}else{
        		$resMsg.html('已经没有更多信息了').show();
        	}
        }
    });
     //点击屏幕其他部位筛选条件div消失
	 // 点击屏幕其他部位筛选条件div消失
	$('#mask').off('tap').on('tap',function(e){
		var $this=$(this);
		$this.hide();
		$myForm.find('.form-hide').hide();
		var optionLis=$parentNav.find("li");
		$.each(optionLis,function(idx,ele){
			if($(ele).hasClass("clear-marker")){
				$(ele).removeClass("marker");
			}else{
				$(ele).removeClass("marker");
			}

		})
		e.cancelBubble=true;
		e.stopPropagation();
		e.preventDefault();
		return false;
	});
});
function buildListDomOfMobileByDataList(options) {
    var dataList=options.dataList||[];
    var imgBasePath=options.imgBasePath||"./";
    var pageTargetType=options.pageTargetType||"_blank";
    var $loading=$(options.loadingSelector);
    var arrTemp=[];
    var dataCount=0;
    $.each(dataList,function (idx, obj) {
        dataCount++;
        var houseAreaText=obj['size']==null||obj['size']===""?"":obj['size']+'m²';//建筑面积
        var houseType=obj['houseType']==null||obj['houseType']===""?"":obj['houseType'];//房屋类型
        var houseFloors='';//房屋楼层
        	houseFloors+=obj['currentFloor']==null||obj['currentFloor']===""?"":obj['currentFloor'];
        	houseFloors+=obj['floors']==null||obj['floors']===""?"":'/'+obj['floors']+'层';
        // var	signTime='';//挂牌时间
        var housereSource="";
        if(obj['houseSource']==null||obj['houseSource']===""){
        	housereSource="";
        }else{
        	housereSource=obj['houseSource']==="fangdd"?"数据来源：房多多":"数据来源："+obj['houseSource'];	
        }
        var imgLinkes="";
        if(!!obj['imgLinks'] && obj['imgLinks']!="null"){
        	imgLinkes='<img src="'+obj['imgLinks']+'" alt="">';
        }else{
        	imgLinkes="暂无图片";
        }
        var listingPriceDom=obj['totalCost']==null? "" : '<span class="totalPrice">'+obj['totalCost']+'万</span>';
        var unitPriceDom=obj['price']==null?"" : '<span class="unit-price">'+obj['price']+'元/m²</span>';
        var tempDom='<li class="panel">'+
                        '<a href="./hangHouseDetail.html?id='+obj['rowKey']+'" target="'+pageTargetType+'">'+
                        	'<div class="cover-image">'+imgLinkes+'</div>'+
                        	'<div class="house-info">'+
                        		'<p class="houseTotrlPrice">'+listingPriceDom+unitPriceDom+'</p>'+
                        		'<p class="houseAddressText">房型：'+houseType+'&nbsp;&nbsp;'+houseAreaText+'</p>'+
                        		'<p class="houseAreaText">楼层：'+houseFloors+'</p>'+
                        		'<p class="housereSource">'+housereSource+'</p>'+
                        	'</div>'+
                    	'</a>'+
                	'</li>';
        arrTemp.push(tempDom) ;
    });
    // $loading.length>0?(dataList.length && dataList.length<10 || dataCount<10 ? $loading.text("已经没有更多信息了").show():$loading.text("").hide()):"无点击加载选择器";
    if($loading.length>0){
    	if(dataList.length && dataList.length<10 || dataCount<10){
    		flag=false; 
    		$loading.text("已经没有更多信息了").show();
    	}else{
    		flag=true;
    		$loading.text("").hide();
    	}
    }
    return arrTemp.join("");
}